import PagePromoterUtil, { PagePromoter } from '../../../data/common/pagePromoter';
import AppSceneUtil, {PageScene} from '../../../data/common/appScene';
import SessionUtil, { JxbHttpClient } from "../../../data/session/session"
import SystemUtil from '../../../shell/system/system';
var App = getApp();
var ApiUrl = App.data.ApiUrl;
var pageSize = App.data.pageSize1;
var Common = require('../../../utils/common.js');

Page({
    data: {
        token: '',
        itemId: 43,
        itemInfo: {},
        carNumber: 1,
        gross: 0.00,

        indicatorDots: true,
        autoplay: false,
        interval: 3000, 
        duration: 500,
        detail: {},

        seckills: true,
        seckill: {},
        limits: false,
        limit: {},

        imageSize: [],
        isShowShoppingchart: false,
        productsList: {},
        productMaskClass: "",
        isShowChartChange: false,
        show_pop: true,
        alert: false,
        isShare:false
    },
    onLoad: function (options) {
        // 开启转发按钮
        PagePromoterUtil.showShareMenu(true).then()
        wx.removeStorageSync('checkedlis');
        SessionUtil.getInstance().then(session => {
            // 注册当前页面的场景信息
            AppSceneUtil.setPageScene(this)
            let sessionUser = session.getTheSessionUserSync()
            this.setData({
                userid: sessionUser.userId
            })
            if (options.itemId) {
                this.setData({
                    itemId: options.itemId
                })
            }
            wx.setNavigationBarTitle({
                title: '商品详情'
            })
            wx.showLoading({
                title: '数据加载中',
            })
            this.productsLists();
            /**分享过来，顾问切换 */
            let pageScene = new PageScene(this)
            if (pageScene.hasPromoter()) {
                this.setData({
                    isShare: true
                })
            } else {
                this.getItemYearList()
                this.itemInfo();
            }
            /**获取屏幕宽度 */
            this.setData({
                w_width: SystemUtil.getSystemInfo(false).windowWidth,
            })
            wx.setStorageSync("if_refresh", 4);
        })

    },

    onShow: function () {
        SessionUtil.getInstance().then(session => {
            // 注册当前页面的场景信息
            AppSceneUtil.setPageScene(this, false)
            this.setData({
                userid: session.getTheSessionUserSync().userId
            })
            this.productsLists();
            this.getItemYearList();
            this.itemInfo();
        })
    },

    // 获取这款酒的年份
    getItemYearList: function () {
        var page = this;
        var itemId = page.data.itemId;
        Common.my_request({
            url: '/AppMaster/Item/getItemYearsList',
            data: {
                item_id: itemId
            },
            success: function (res) {
                if (res.data.result == 0) {
                    var list = res.data.data.item_year_list;
                    if (list.length > 0) {
                        page.setData({
                            list_year: list
                        })
                    }
                }
            }
        })
    },
    // 点击年份切换商品
    changeYear: function (e) {
        var page = this;
        page.setData({
            choosed: 0
        });
        var id = e.currentTarget.id;
        var products = page.data.productsList.productsList;
        if (id == page.itemId) {
            return false;
        } else {
            page.setData({
                itemId: id
            })
        }
        page.itemInfo();
        for (var i = 0; i < products.length; i++) {
            if (products[i].itemid == id) {
                page.setData({
                    choosed: products[i].carNumber,
                });
            }
        }
    },
    itemInfo: function (action = '') {
        // 加载详情
        var page = this;
        var itemId = page.data.itemId;
        if (action == 'Refresh') {
            wx.stopPullDownRefresh();
        }
        Common.my_request({
            url: '/AppMaster/Item/itemDetail',
            data: {
                itemId: itemId
            },
            success: function (res) {
                console.log(res);
                if (res.data.result == 0) {
                    var Product = res.data.data;
                    if (!Product) {
                        var isShare = page.data.isShare;
                        if (!isShare) {
                            Common.Alert('错误提示', res.data.message);
                            wx.hideLoading();
                            var pages = getCurrentPages();
                            if (pages.length > 2) {
                                wx.navigateBack()
                            } else {
                                wx.switchTab({
                                    url: '/pages/index/index',
                                })
                            }
                            return;
                        } else {
                            page.setData({
                                isShare:false
                            })
                        }
                    }
                    var str = Product.detail;
                    var reg = /(http.*?(jpg|jpeg|gif|png))/ig;
                    var result = str.match(reg);
                    if (Product.activity_list.length > 0) {
                        var a = Product.activity_list
                        for (var i = 0; i < a.length; i++) {

                            if (a[i].activity_category == 6) {
                                page.setData({
                                    seckill: a[i],
                                    seckills: false,
                                });
                                var c = a[i].activity_end_second
                                var b = setInterval(function () {
                                    c--
                                    if (c >= 0) {
                                        page.setData({
                                            endDate: page.ShowCountDown(c),
                                        });
                                    } else {
                                        clearTimeout(b);
                                        page.itemInfo()
                                    }
                                }, 1000);
                            } else if (a[i].activity_category == 4) {
                                    page.setData({
                                    limit: a[i],
                                    limits: true,
                                });
                            }
                        }
                    } else {
                        page.setData({
                            seckills: true,
                        });
                    }
                    page.setData({
                        itemInfo: Product,
                        detail: result,
                    });
                    // 关闭加载
                    wx.hideLoading();
                } else {
                    console.log(res.data.message);
                    Common.Alert('错误提示', res.data.message);
                    wx.hideLoading();
                    var pages = getCurrentPages();
                    if (pages.length > 2) {
                        wx.navigateBack()
                    } else {
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    }
                    return;
                }
            }
        });
    },
    ShowCountDown: function (endDate) {
        //倒计时
        var leftsecond = parseInt(endDate);
        //var day1=parseInt(leftsecond/(24*60*60*6)); 
        var day1 = Math.floor(leftsecond / (60 * 60 * 24));
        var hour = Math.floor((leftsecond) / 3600) + '';
        var hour1 = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
        var minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600) / 60) + '';
        var second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour1 * 3600 - minute * 60) + '';
        var divname = {};
        divname.hour = hour.length < 2 ? ('0' + hour) : hour;
        divname.minute = minute.length < 2 ? ('0' + minute) : minute;
        divname.second = second.length < 2 ? ('0' + second) : second;
        return divname;
    },
    onPullDownRefresh: function () {
        // 下拉刷新
        var page = this;
        wx.showLoading({
            title: '数据加载中',
        })
        page.itemInfo('Refresh');
    },
    imageLoad: function (e) {

        var index = e.currentTarget.id;;
        var page = this;
        var imageHeight = page.data.imageSize;
        imageHeight[index] = Common.imageLoadAn(e,(page.data.w_width-20)).toFixed(2);
        page.setData({
            imageSize: imageHeight
        })
    },
    onShareAppMessage: function () {
        // 构造并返回自定义数据
        return (new PagePromoter( this.route, { itemId : this.data.itemId }))
        .setShareTitle(this.data.itemInfo.productName)
        .buildShareInfo()
    },
    // 显示数量修改面板
    show_count: function () {
        if (!this.productNums()) {
            return false;
        }
        var page = this;
        page.setData({
            show_pop: !page.data.show_pop
        })
    },
    AddCart: function (e) {
        var page = this;
        var ID = e.currentTarget.id
        var itemId = ID.split('-')[0];
        var stock = ID.split('-')[1];
        if (stock == 0) {
            wx.showToast({
                title: '库存不足！',
                image: '../../images/fail.png',
                duration: 2000
            })
        } else {
            Common.my_request({
                url: '/AppMaster/PosCart/PosAddCart', //仅为示例，并非真实的接口地址
                data: {
                    number: 1,
                    itemId: itemId
                },
                success: function (res) {
                    if (res.data.result == 0) {
                        wx.showToast({
                            title: '添加成功',
                            icon: 'success',
                            duration: 2000
                        })
                        page.productsLists();
                    } else {
                        wx.showToast({
                            title: '添加失败',
                            image: '../../images/fail.png',
                            duration: 2000
                        })
                    }
                }
            })
        }
    },
    // 查看优惠券
    coupon: function () {
        var page = this,
            coupon_json = {},
            coupon_array = [],
            detail = page.data.itemInfo;
        coupon_json.item_id = detail.itemId;
        coupon_json.count = page.data.choosed;
        coupon_json.price = detail.promotePrice;

        coupon_array.push(coupon_json);
        coupon_array = JSON.stringify(coupon_array);
        var userid = wx.getStorageSync('user_id');
        if (userid < 0) {
            wx.navigateTo({
                url: '/pages/my/logintype/logintype?from=1&coupon_array=' + coupon_array
            });
        } else {
            wx.navigateTo({
                url: '/pages/coupon/use/use?coupon_array=' + coupon_array + '&is_useCoupon=showAllCoupon'
            })
        }
        
    },
    
    numberReduce: function () {
        var page = this;
        var cnumber = page.data.carNumber;
        cnumber--;
        if (cnumber >= 1) {
            page.setData({
                carNumber: cnumber
            })
        }
    },
    purchase: function () {
        if (!this.productNums()) {
            return false;
        }
        var page = this;
        var userid = page.data.userid;
        if (userid < 0) {
            wx.navigateTo({
                url: '/pages/my/logintype/logintype?from=0&checkedlis=' + page.data.itemId
            });
        } else {
            Common.my_request({
                url: '/AppMaster/PosCart/PosAddCart', //仅为示例，并非真实的接口地址
                data: {
                    number: 1,
                
                    itemId: page.data.itemId
                },
                success: function (res) {
                    if (res.data.result == 0) {
                        wx.navigateTo({
                            url: '/pages/product/orderConfirm/index?checkedlis=' + page.data.itemId
                        });
                        page.productsLists();
                    } else {
                        wx.showToast({
                            title: res.data.message,
                            image: '../../images/fail.png',
                            duration: 2000
                        })
                    }
                }
            })
        }
    },
    clearStorageSync: function () {
        wx.setStorageSync("dilivery", '');
        wx.setStorageSync("invoice", {});
        wx.setStorageSync("pay", {});
    },
    productsLists: function () {
        this.setData({
            choosed: 0,
        });
        (new JxbHttpClient).get('AppMaster/PosCart/cartDetail').then(jxbResp=>{
            let respData = jxbResp.data, products = respData.productsList, list = respData.activity_list
            let total = 0, gross = 0.00, itemids = [], limits = [];
            for (let z = 0; z < list.length; z++) {
                if (list[z].activity_category == 6) {
                    itemids = itemids.concat(list[z].itemids);
                }
                if (list[z].activity_category == 4) {
                    limits = limits.concat(list[z].itemids);
                }
            }
            for (let i = 0; i < products.length; i++) {
                total = total + products[i].carNumber;
                gross = gross + products[i].carNumber * products[i].show_price;
                if (products[i].itemid == this.data.itemId) {
                    // carNumber: products[i].carNumber,
                    this.setData({
                        carNumber: 1,
                        choosed: products[i].carNumber,
                        cartId: products[i].cartId,
                    });
                }
                let z = Common.contains(itemids, products[i].itemid),
                    w = Common.contains(limits, products[i].itemid);
                if (z && w) {
                    products[i].activity_list = ['秒杀', '限购']
                } else {
                    if (z) {
                        products[i].activity_list = ['秒杀'];
                    }
                    if (w) {
                        products[i].activity_list = ['限购'];
                    }
                }
            }
            respData.total = total;
            respData.gross = gross.toFixed(2);
            respData.productsList = products;
            this.setData({
                productsList: respData,
            })
        }).catch(err=>{
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
              })
            this.setData({
                productsList: {},
                carNumber: 1,
            })
        })
    },
    shoppingChartList: function () {
        var page = this;
        var isShowShoppingchart = page.data.isShowShoppingchart;
        var bIsShowShoppingchart = isShowShoppingchart ? false : true;
        page.setData({
            isShowShoppingchart: bIsShowShoppingchart,
            productMaskClass: bIsShowShoppingchart ? "product-mask" : ""
        })
    },
    // 输入框失焦置0
    resetTozero: function (e) {
        this.setData({
            carNumber: e.detail.value == "" ? 0 : e.detail.value
        })
    },
    /**
     *  更新数量
     */
    updateInput: function (e) {
        this.setData({
            carNumber: e.detail.value
        })
    },
    // 输入框数量加一
    numberAdd: function (e) {
        var page = this;
        var cnumber = page.data.carNumber;
        cnumber++;
        if (cnumber >= 0) {
            page.setData({
                carNumber: cnumber
            })
        }
    },
    shoppingCartAdd: function (e) {
        var page = this;
        var d = e.currentTarget.id;
        var itemId = d.split('_')[0];
        var fromData = d.split('_')[1];
        if(!this.productNums()){
            return false;
        }
        if (fromData == 1) {
            var number = page.data.carNumber;
        } else {
            var number = 1;
        }
        Common.my_request({
            url: '/AppMaster/PosCart/PosAddCart', //仅为示例，并非真实的接口地址
            data: {
                number: number,
                itemId: itemId
            },
            success: function (res) {
                if (res.data.result == 0) {
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success',
                        duration: 2000
                    })
                    page.productsLists();
                    page.setData({
                        show_pop: true,
                        alert: true
                    })
                } else {
                    wx.showToast({
                        title: res.data.message,
                        image: '../../images/fail.png',
                        duration: 2000
                    })
                }
            }
        });
    },

    goCarts: function () {
        wx.switchTab({
            url: '/pages/shoppingcart/index'
        })
    },
    toIndex(){
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    productNums:function(){
        var a = false;
        if (this.data.itemInfo.productNums < 1) {
            wx.showToast({
                title: '库存不足！',
                image: '../../images/fail.png',
                duration: 2000
            })
        } else {
            a = true;
        }
        return a;
    }
})